'use strict'

let callback = {}

class Transport {
  constructor(socket, factory) {
    this.socket = socket
    this.factory = factory
    this._reqId = 0
    let self = this
    socket.on('data', function(data, reqId, msgName) {
      self.msgResolve(data, reqId, msgName)
    })

    socket.on('error', function(data) {

    })

    socket.on('close', function(data) {

    })
  }

  //消息解析
  msgResolve(msg, reqId, msgName) {
    let msgData = JSON.parse(msg) //数据包体
    let self = this
    if (msgName) {
      //调用为远程请求注册的函数
      let remoteMethod = this.factory.getRemoteMothed(msgName) //获取调用的方法
      if (remoteMethod) {
        remoteMethod(this, msgData, function(result) {
          if (result) {
            this._send(result, reqId, 0)
          }
        })
      }
    } else {
      //远程返回数据时，调用对应的回调函数
      if (callback[reqId]) {
        callback[reqId](msgData)
        delete callback[reqId]
      }
    }
  }

  //发送数据的接口
  _send(data, reqId, msgName) {
    if (typeof data !== 'string') {
      data = JSON.stringify(data)
    }
    this.socket.send(data, reqId, msgName)
  }

  //执行远程调用
  callRemote(msgName, msgBody, cb) {
    let reqId = 0
    if (cb) {
      reqId = Math.floor(++this._reqId % 32767)
      callback[reqId] = cb
    }
    this._send(msgBody, reqId, msgName)
  }

  //断开连接
  close() {
    this.socket.close()
  }
}

module.exports = Transport
